﻿using ICSharpCode.SharpZipLib.Zip;
using PFMCandidate;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFMHandlers
{
   public  class PFMUnZipHandler:PFMHandler
    {
       public override byte[] Perform(Candidate aCandidate, byte[] baTarget)
       {
           PFMFileHandler pFHandler = new PFMFileHandler();
           baTarget = GetProcessingData(aCandidate, baTarget);
           byte[] unzipResult = null;
           try
           {
               MemoryStream ms = new MemoryStream(baTarget);
               ZipEntry theEntry;
               using (ZipInputStream zipStream = new ZipInputStream(ms))
               {
                   while ((theEntry = zipStream.GetNextEntry()) != null)
                   {
                       using (MemoryStream msDes = new MemoryStream())
                       {
                           byte[] data = new byte[2048];
                           int size;
                           while (true)
                           {
                               size = zipStream.Read(data, 0, data.Length);
                               if (size > 0)
                               {
                                   msDes.Write(data, 0, size);
                               }
                               else { break; }
                           }
                           unzipResult = msDes.ToArray();
                       }
                   }
                   zipStream.Close();
               }
           }
           catch
           {
               unzipResult = null;
           }
          pFHandler.Perform(aCandidate, unzipResult);
           return baTarget;
       }
    }
}
